from datetime import datetime, timedelta
from itertools import chain
from django.db.models import Q
from operator import attrgetter
from pypinyin import pinyin

from NewFlowLogic.models import ThreePartyAttendanceInformation
from ios_api.models import ScanCode
from medical_ethics.models import EvaluationOfMedicalEthics
from administrative.models import Company, Topicsattachments, OfficialDocuments, VehicleApply, Topics, ConferenceMemo, \
    GatheringApply, OfficialDocumentsPeople, ConferenceMemoPeople
from back_management.models import topic_meeting, VoteLeader, topic_sing
import xlrd, re, uuid, urllib.parse, time, hashlib, base64, xlwt, json, qrcode
from finance.models import TravelReimbursement, CheckWorkAttendance, CheckWorkTable, CheckWorkRecord, TravelApply, \
    BusinessContract, MedicalMaterials, LogisticsOffice, NutritionalMeals, GeneralFinance, LeaveRequest, Dimission, \
    NewMedicalServices, SurgicalGrading, SoloPracticeApply, OutgoingCadresData, LaborUnionExpenses, SealMaking, \
    SubjectFunding, QuickAuthorization, BookSubscription, PartyBuilding, QuickAuthorizationSeal, CheckWorkLaborDispatch, \
    QuickAuthorizationApplicationCategory
from personal_center.creat_excel import attendance_sheet
from personal_center.models import BillGroup, Function, seal, ConferenceRoomApplication, SealApply, FixedAssets, \
    SealApplyAuditRecord, SortLine
from Administrative_office_system.utils.views import GetGroupView
from Administrative_office_system.utils.pic_to_png import transparent_background
from Administrative_office_system.utils.views import LoginRequiredMixin
from personal_center.models import User
from announcements.models import NoticePeople, Notice
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from Oa_system.models import *
# Create your views here.
from personal_center.sql_file import manage_flow
from personnel.models import DutyTime
from supervision_inspection.models import AttendedMeeting
from system_setup.models import CustomerForm, LowCodeBill, LowCodeBillAuditRecord, CustomerFormModule, punch_clock
from system_setup.utils import deal_templates_html, deal_process_html, new_flow_node
from system_setup.create_directory import *
from django.http import StreamingHttpResponse


def num_to_char(num):
    if num == 1:
        return '星期一'
    elif num == 2:
        return '星期二'
    elif num == 3:
        return '星期三'
    elif num == 4:
        return '星期四'
    elif num == 5:
        return '星期五'
    elif num == 6:
        return '星期六'
    else:
        return '星期日'


class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/home.html",{'realname': real_name, 'position': position, 'department': department})

# 组织架构
class organization(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/organization.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        industry_title = request.POST.get("industry_title", None)               # 部门名称
        superior_department = request.POST.get("superior_department", None)             # 上级部门
        principal = request.POST.get("principal", None)                 # 部门负责人
        dep_id = request.POST.get("dep_id", None)               # 删除部门所需ID
        if industry_title and superior_department and principal:
            parent_id = Department.objects.get(name=superior_department).id
            obj = Department.objects.create(name=industry_title, parent_id=parent_id, principal=principal)           # 数据入库
            obj.save()

        # 删除部门
        elif dep_id:
            obj = Department.objects.get(id=dep_id)     # 获取部门
            obj.delete()        # 删除部门

        alldata = Department.objects.all()         # 查询所有数据
        returnDict, tree_data, check_dict = {}, [], {}

        # 构建json数据返回前端
        for dat in alldata:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["pId"] = dat.parent_id
            one_dict["name"] = dat.name
            one_dict["open"] = True

            if str(dat.parent_id) != "0":
                check_dict[str(dat.id)] = [dat.name, Department.objects.get(id=dat.parent_id).name, dat.principal]
            else:
                check_dict[str(dat.id)] = [dat.name, "", dat.principal]
            tree_data.append(one_dict)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["data"] = [{"tree_data": tree_data, "check_dict": check_dict}]
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 岗位设置
class set_up(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/set_up.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        parent = request.POST.get("parent", None)       # 所属部门
        stationNum = request.POST.get("stationNum", None)           # 岗位编号
        stationName = request.POST.get("stationName", None)              # 岗位名称
        category = request.POST.get("category", None)               # 岗位类别
        position_statement = request.POST.get("position_statement", None)           # 岗位职责
        job_description = request.POST.get("job_description", None)         # 岗位描述
        page = request.POST.get("page", None)           # 页码
        delete_list = request.POST.get("delete_list", None)             # 删除数据id列表
        if delete_list:
            station_table.objects.filter(stationNum__in=delete_list.split(",")).delete()            # 批量删除数据

        if parent and stationName and category:
            # 数据入库
            obj = station_table.objects.create(stationName=stationName, stationNum=stationNum, category=category, parent=parent, position_statement=position_statement, job_description=job_description)  # 数据入库
            obj.save()

        # 查询数据构建界面展示JSON
        all_data = station_table.objects.all()
        count_num = all_data.count()
        returnDict, returnList = {}, []
        for dat in all_data[(int(page)-1)*20:int(page)*20]:
            one_dict = {}
            one_dict["parent"] = dat.parent
            one_dict["stationNum"] = dat.stationNum
            one_dict["stationName"] = dat.stationName
            one_dict["category"] = dat.category
            one_dict["position_statement"] = dat.position_statement
            one_dict["job_description"] = dat.job_description
            returnList.append(one_dict)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = returnList
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 新建角色
class new_role(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/new_role.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        returnDict, model_list, name_dict = {}, [], {}
        genre_type = request.POST.get("genre_type", None)           # 请求类型；1、模块请求；2、数据存储
        if genre_type == "2":
            stationName = request.POST.get("stationName", None)         # 角色名称
            permission = request.POST.get("permission", None)           # 权限字符串
            remark = request.POST.get("position_statement", None)       # 备注
            obj = role_permission.objects.create(character=stationName, permission=permission, remark=remark)           # 数据入库
            obj.save()

        all_model_list = model_name.objects.all()           # 查询所有模块名称
        for models in all_model_list:
            one_dict = {}
            one_dict["modelId"] = models.id             # 模块ID
            one_dict["modelName"] = models.name         # 模块名称
            model_list.append(one_dict)

            model_sun_model = submodule.objects.filter(parent_module_id=models.id)
            name_list = []
            for t in model_sun_model:
                name_list.append(t.name)
            name_dict[str(models.id)] = name_list

        returnDict["model_list"] = model_list
        returnDict["name_dict"] = name_dict
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 新建用户
class new_user(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        return render(request, "system_setup/new_user.html", {'realname': real_name, 'position': position, 'department': department, "company_list": company_list})

    def post(self, request):
        real_name = request.POST.get('real_name') # 真实姓名
        username= request.POST.get('username') # 账户名
        password = request.POST.get('password') # 账号密码
        department = request.POST.get('department') # 部门
        gender = request.POST.get('gender') # 性别
        education = request.POST.get('education','') # 学历
        marital_status = request.POST.get('marital_status','') # 婚姻状态
        political_outlook = request.POST.get('political_outlook','') # 政治面貌
        nation = request.POST.get('nation','') # 民族
        ID_number = request.POST.get('ID_number','') # 身份证号
        native_place = request.POST.get('native_place','') # 籍贯
        major = request.POST.get('major','') # 专业
        graduated_university = request.POST.get('graduated_university','') # 毕业院校
        position = request.POST.get('position','') # 职位
        home_address = request.POST.get('home_address','') # 家庭住址
        mobile = request.POST.get('mobile','') # 手机号码
        mailbox = request.POST.get('mailbox','') # 邮箱
        remarks = request.POST.get('remarks','') # 备注
        signature_picture = request.POST.get('signature_picture') # 签名图片
        enclosure = request.FILES.get('enclosure') # 附件

        if not all([real_name,username,password,department,gender]):
            returnDict = {"code": 400, "message": "缺少必传参数"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # 2.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{2,20}$', username):
            returnDict = {'code': 400, 'message': '账号格式有误,2至20位字母数字构成'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if not re.match(r'^[a-zA-Z0-9]{6,20}$', password):
            returnDict = {'code': 400, 'message': '密码格式有误,6至20位字母数字构成'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if ID_number:
            if len(ID_number) != 18 and len(ID_number) != 15:
                returnDict = {'code': 400, 'message': '身份证长度有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mailbox:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', mailbox):
                returnDict = {'code': 400, 'message': '邮箱格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            returnDict = {'code': 400, 'message': '访问数据库失败','data':str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if count > 0:
            try:
                del_count = User.objects.filter(username=username,is_delete=1).count()
            except Exception as e:
                returnDict = {'code': 400, 'message': '访问数据库失败', 'data': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if del_count >0:
                try:
                    User.objects.filter(username=username).delete()
                except Exception as e:
                    returnDict = {'code': 400, 'message': '访问数据库失败', 'data': str(e)}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                returnDict = {'code': 400, 'message': '该账号已经存在，不能重复注册'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mobile:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                returnDict = {'code': 400, 'message': 'mobile格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if gender == '男':
            gender = 'male'
        elif gender == '女':
            gender = 'female'
        else:
            returnDict = {'code': 400, 'message': '性别有误'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if marital_status:
            if marital_status == '已婚':
                marital_status = 'married'
            elif marital_status == '未婚':
                marital_status = 'single'
            else:
                returnDict = {'code': 400, 'message': '婚姻状态有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if political_outlook:
            if political_outlook not in ['群众','团员','党员']:
                returnDict = {'code': 400, 'message': '政治面貌有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            user = User.objects.create_user(username=username,
                                            job_number=username,
                                            real_name=real_name,
                                            password=password,
                                            mobile=mobile,
                                            department=department.split("(")[0],
                                            gender=gender,
                                            education=education,
                                            marital_status=marital_status,
                                            nation=nation,
                                            political_outlook=political_outlook,
                                            ID_number=ID_number,
                                            native_place=native_place,
                                            major=major,
                                            graduated_university=graduated_university,
                                            position=position,
                                            home_address=home_address,
                                            mailbox=mailbox,
                                            remarks=remarks,
                                            enclosure=enclosure,
                                            signature_picture=signature_picture,
                                            group_id='6',
                                            company_id=department.split("(")[1].replace(")", "")
                                            )
        except Exception as e:
            returnDict = {'code': 400, 'message': '保存到数据库出错', 'data': str(e)}

            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            if signature_picture:
                user.signature_picture = signature_picture
                user.save()
        except Exception as e:
            returnDict = {'code': 400, 'message': '保存签名图片失败', 'data': str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



class user_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        return render(request, "system_setup/user_list.html", {'realname': real_name, 'position': position, 'department': department, "company_list": company_list})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_value = request.POST.get("search_value", "")
        all_data = User.objects.filter(~Q(real_name='管理员'), Q(real_name__contains=search_value) | Q(department__contains=search_value), is_delete=0).all().order_by('id')

        count_num = all_data.count()
        returnList, user_index = [], 0
        for dat in all_data[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["real_name"] = dat.real_name
            one_dict["job_number"] = dat.job_number
            one_dict["username"] = dat.username
            one_dict["mobile"] = dat.mobile
            one_dict["mailbox"] = dat.mailbox
            one_dict["department"] = dat.department
            one_dict["position"] = dat.position
            one_dict["gender"] = '男' if dat.gender == 'male' else '女'
            one_dict["education"] = dat.education
            one_dict["marital_status"] = '单身' if dat.marital_status == 'single' else '已婚'
            one_dict["political_outlook"] = dat.political_outlook
            one_dict["nation"] = dat.nation
            one_dict["ID_number"] = dat.ID_number
            one_dict["native_place"] = dat.native_place
            one_dict["major"] = dat.major
            one_dict["graduated_university"] = dat.graduated_university
            one_dict["home_address"] = dat.home_address
            one_dict["remarks"] = dat.remarks
            one_dict["personnel_category"] = dat.personnel_category
            one_dict["user_index"] = user_index

            if dat.signature_picture:
                signature_picture_url = '/media/' + str(dat.signature_picture)
            else:
                signature_picture_url = ''
            if dat.enclosure:
                enclosure_url = '/media/' + str(dat.enclosure)
            else:
                enclosure_url = ''
            one_dict["signature_picture"] = signature_picture_url
            one_dict["enclosure"] = enclosure_url
            returnList.append(one_dict)
            user_index += 1

        return_dict = {
            'code': 200,
            'message': 'success',
            "data": returnList, "totals": count_num
        }
        return HttpResponse(json.dumps(return_dict), content_type="application/json")

# 角色列表
class role_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/role_list.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        returnDict = {}
        page = request.POST.get("page", None)  # 页码
        delete_list = request.POST.get("delete_list", None)  # 删除数据id列表
        if delete_list:
            for id_ in [int(i) for i in delete_list.split(",")]:
                role_permission.objects.filter(id=id_).delete()  # 批量删除数据

        # 查询数据构建界面展示JSON
        all_data = role_permission.objects.all()
        count_num = all_data.count()
        returnDict, returnList = {}, []
        for dat in all_data[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["character"] = dat.character
            one_dict["permission"] = dat.permission
            one_dict["remark"] = dat.remark
            returnList.append(one_dict)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = returnList
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 角色权限关联
class permissions_associated(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "system_setup/permissions_associated.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

# 角色关联列表
class linked_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "system_setup/linked_list.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})


# 查询用户
class UserListView(View):
    def get(self, request):
        query_type = request.GET.get('query_type')  # 查类型
        query_value = request.GET.get('query_value')  # 查询值
        page = request.GET.get("page", '')  # 页码
        if not page:
            page = '1'
        if query_type:
            if query_value:
                if query_type=='请选择查询类型':
                    all_data = User.objects.filter(is_delete=0).all()
                elif query_type == 'real_name':
                    all_data = User.objects.filter(is_delete=0, real_name__icontains=query_value).all()
                elif query_type == 'username':
                    all_data = User.objects.filter(is_delete=0, username__icontains=query_value).all()
                elif query_type == 'mobile':
                    all_data = User.objects.filter(is_delete=0, mobile__icontains=query_value).all()
                elif query_type == 'mailbox':
                    all_data = User.objects.filter(is_delete=0, mailbox__icontains=query_value).all()
                elif query_type == 'department':
                    all_data = User.objects.filter(is_delete=0, department__icontains=query_value).all()
                elif query_type == 'position':
                    all_data = User.objects.filter(is_delete=0, position__icontains=query_value).all()
                elif query_type == 'ID_number':
                    all_data = User.objects.filter(is_delete=0, ID_number__icontains=query_value).all()
                elif query_type == 'gender':
                    if query_value == '男':
                        query_value = 'male'
                    elif query_value == '女':
                        query_value = 'female'
                    all_data = User.objects.filter(is_delete=0, gender=query_value).all()
                elif query_type == 'education':
                    all_data = User.objects.filter(is_delete=0, education=query_value).all()
                elif query_type == 'marital_status':
                    if query_value == '未婚':
                        query_value = 'single'
                    elif query_value == '已婚':
                        query_value = 'married'
                    all_data = User.objects.filter(is_delete=0, marital_status=query_value).all()
                elif query_type == 'political_outlook':
                    all_data = User.objects.filter(is_delete=0, political_outlook=query_value).all()
                elif query_type == 'nation':
                    all_data = User.objects.filter(is_delete=0, nation=query_value).all()
                elif query_type == 'native_place':
                    all_data = User.objects.filter(is_delete=0, native__place_icontains=query_value).all()
                elif query_type == 'major':
                    all_data = User.objects.filter(is_delete=0, major=query_value).all()
                elif query_type == 'graduated_university':
                    all_data = User.objects.filter(is_delete=0, graduated__university_icontains=query_value).all()
                elif query_type == 'home_address':
                    all_data = User.objects.filter(is_delete=0, home_address__contains=query_value).all()
                else:
                    all_data = User.objects.filter(is_delete=0).all()
            else:
                all_data = User.objects.filter(is_delete=0).all()
        else:
            all_data = User.objects.filter(~Q(real_name='管理员'), is_delete=0).all().order_by('id')

        count_num = all_data.count()
        returnList = []
        for dat in all_data[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["real_name"] = dat.real_name
            one_dict["job_number"] = dat.job_number
            one_dict["username"] = dat.username
            one_dict["mobile"] = dat.mobile
            one_dict["mailbox"] = dat.mailbox
            one_dict["department"] = dat.department
            one_dict["position"] = dat.position
            one_dict["gender"] = '男' if dat.gender == 'male' else '女'
            one_dict["education"] = dat.education
            one_dict["marital_status"] = '单身' if dat.marital_status == 'single' else '已婚'
            one_dict["political_outlook"] = dat.political_outlook
            one_dict["nation"] = dat.nation
            one_dict["ID_number"] = dat.ID_number
            one_dict["native_place"] = dat.native_place
            one_dict["major"] = dat.major
            one_dict["jon_degree"] = dat.jon_degree
            one_dict["graduated_university"] = dat.graduated_university
            one_dict["home_address"] = dat.home_address
            one_dict["remarks"] = dat.remarks
            one_dict["personnel_category"] = dat.personnel_category

            if dat.signature_picture:
                signature_picture_url = '/media/'+str(dat.signature_picture)
            else:
                signature_picture_url = ''
            if dat.enclosure:
                enclosure_url = '/media/' + str(dat.enclosure)
            else:
                enclosure_url = ''
            one_dict["signature_picture"] = signature_picture_url
            one_dict["enclosure"] = enclosure_url
            returnList.append(one_dict)

        return_dict = {
            'code': 200,
            'message': 'success',
            'data': {
                'count_num': count_num,
                'user_li': returnList,
                }
        }

        return HttpResponse(json.dumps(return_dict), content_type="application/json")

    # 用户数据修改
    def post(self, request):
        real_name = request.POST.get('real_name')  # 真实姓名
        username = request.POST.get('username', "admin")  # 账户名
        department = request.POST.get('department')  # 部门
        gender = request.POST.get('gender', '')         # 性别
        education = request.POST.get('education', '')  # 学历
        marital_status = request.POST.get('marital_status', '')  # 婚姻状况
        political_outlook = request.POST.get('political_outlook', '')  # 政治面貌
        nation = request.POST.get('nation', '')  # 民族
        ID_number = request.POST.get('ID_number', '')  # 身份证号
        native_place = request.POST.get('native_place', '')  # 籍贯
        major = request.POST.get('major', '')  # 专业
        graduated_university = request.POST.get('graduated_university', '')  # 毕业院校
        position = request.POST.get('position', '')  # 职位
        home_address = request.POST.get('home_address', '')  # 家庭住址
        mobile = request.POST.get('mobile', '')  # 手机号码
        mailbox = request.POST.get('mailbox', '')  # 邮箱
        remarks = request.POST.get('remarks', '')  # 备注
        birthday = request.POST.get('birthday', '')  # 生日
        age = request.POST.get('age', '')  # 年龄
        postJob = request.POST.get('postJob', '')  # 岗位
        wechat_number = request.POST.get('wechat_number', '')  # 微信
        QQ_number = request.POST.get('QQ', '')                     # QQ号

        if not all([real_name, username, department]):
            returnDict = {'code': 400, 'message': '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # 2.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{2,20}$', username):
            returnDict = {'code': 400, 'message': '账号格式有误,2至20位字母数字构成'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mailbox:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', mailbox):
                returnDict = {'code': 400, 'message': '邮箱格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            returnDict = {'code': 400, 'message': '访问数据库失败', 'data': str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if count == 0:
            returnDict = {'code': 400, 'message': '未找到该账户'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mobile:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                returnDict = {'code': 400, 'message': 'mobile格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # try:
        user_query_set = User.objects.filter(username=username)
        for user in user_query_set:
            if mobile:
                user.mobile = mobile
            if gender:
                user.gender = gender
            if marital_status:
                user.marital_status = "single" if marital_status == "单身" else "married"
            if nation:
                user.nation = nation
            if ID_number:
                user.ID_number = ID_number
            if native_place:
                user.native_place = native_place
            if major:
                user.major = major
            if graduated_university:
                user.graduated_university = graduated_university
            if home_address:
                user.home_address = home_address
            if remarks:
                user.remarks = remarks
            if department and "(" in department:
                user.department = department.split("(")[0]
                user.company = Company.objects.get(id=department.split("(")[1].replace(")", ""))
            if birthday:
                user.birthday = birthday
            if education:
                user.education = education
            if age:
                user.age = age
            if postJob:
                user.post = postJob
            if political_outlook:
                user.political_outlook = political_outlook
            if wechat_number:
                user.wechat_number = wechat_number
            if QQ_number:
                user.QQ = QQ_number
            if position:
                user.position = position
            if mailbox:
                user.mailbox = mailbox
            user.save()
        # except Exception as e:
        #     print(e)
        #     returnDict = {'code': 400, 'message': '修改信息失败','data': str(e)}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {'code': 200, 'message': 'success'}
        request.user.mobile=mobile
        request.user.birthday = birthday
        request.user.education = education
        request.user.age = age
        request.user.post = postJob
        request.user.political_outlook = political_outlook
        request.user.wechat_number = wechat_number
        request.user.QQ_number = QQ_number
        request.user.post = position
        request.user.mailbox = mailbox
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class UpdateSignaturePictureView(LoginRequiredMixin,View):
    def get(self,request):
        returnDict = {'code': 200, 'message': 'success', 'data': ''}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")
    def post(self, request):
        username = request.POST.get('username')  # 账户名
        signature_picture = request.FILES.get('files')  # 签名图片
        add_user = request.POST.get('add_user', None)  # 添加用户标识
        return_data = {
            'signature_picture': ''
        }
        if add_user:
            data = "%s_%d" % (signature_picture.name, int(time.time()))
            file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
            pic_path = os.getcwd() + "/media/signature_picture/" + time.strftime("%Y", time.localtime()) + "/" + time.strftime("%m", time.localtime()) + "/" + file_hash + os.path.splitext(signature_picture.name)[-1]
            with open(pic_path, 'wb') as f:  # w是写，b是二进制，以wb方式打开文件，是往文件写入二进制数据
                f.write(signature_picture.read())
            new_path = transparent_background(pic_path)
            return_data["signature_picture"] = new_path.replace(os.getcwd(), "")
            returnDict = {'code': 200, 'message': 'success', 'data': return_data}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if not all([username, signature_picture]):
            returnDict = {'code': 400, 'message': '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if request.user.username not in ['admin', username]:
            returnDict = {'code': 400, 'message': '您无权修改他人签名'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        user_query_set = User.objects.filter(username=username)

        for user in user_query_set:
            user.signature_picture = signature_picture
            user.save()
            # 将图片转换为PNG
            cwd_path = os.getcwd()
            new_cwd_path = cwd_path.replace('\\','/')
            old_path = new_cwd_path+'/media/'+str(user.signature_picture)
            return_path  = transparent_background(old_path)
            if return_path:
                signature_picture_path = return_path.split('/media/')[-1]
                user.signature_picture = signature_picture_path
                user.save()

            return_data['signature_picture'] = '/media/'+str(user.signature_picture)
            request.user.signature_picture = user.signature_picture
        returnDict = {'code': 200, 'message': 'success', 'data': return_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



# 组织架构录入
class DepartmentImportApiView(View):
    def post(self,request):
        # item  = json.loads(request.body)
        all_dict  = json.loads(request.body)

        # 二级的录入
        # {'序号': '', '一级': '', '二级': '院长助理（朱斌）', '三级': '', '部门名称': '', '负责人': '', '部门属性': '', '成立日期': '', '撤销日期': '', '备注': '', '部门英文名称': '', '部门全称'
        # aa = Department.objects.get(id=1)
        # Department.objects.create(
        #     name=item['二级'],
        #     parent=aa,
        #     principal=item['负责人'],
        #     level= 2,
        #     department_code='',
        #     department_attribute=item['部门属性'],
        #     incorporation_date=item['成立日期'],
        #     cancellation_date=item['撤销日期'],
        #     department_english_name=item['部门英文名称'],
        #     department_full_name=item['部门全称'],
        # )
        returnDict = {'code': 200, 'message': 'success'}
        # # 三级导入
        # # {'序号': '99', '一级': '', '二级': '', '三级': '137', '部门名称': '应急办', '负责人': '', '部门属性': '',
        # # '成立日期': '2020-01-31', '撤销日期': '', '备注': '', '部门英文名称': '', '部门全称': '临床服务类科室/应急办'}
        # for key,items in all_dict.items():
        #     print(key)
        #     aa = Department.objects.get(name=key)
        #     for item in items:
        #         Department.objects.create(
        #             name=item['部门名称'],
        #             parent=aa,
        #             principal=item['负责人'],
        #             level= 3,
        #             department_code='',
        #             department_attribute=item['部门属性'],
        #             incorporation_date=item['成立日期'],
        #             cancellation_date=item['撤销日期'],
        #             department_english_name=item['部门英文名称'],
        #             department_full_name=item['部门全称'],
        #         )

        return HttpResponse(json.dumps(returnDict), content_type="application/json")



# 部门表录入
class DepartmentDetailImportApiView(View):
    def post(self,request):
        # item  = json.loads(request.body)
        item  = json.loads(request.body)
        DepartmentDetail.objects.create(
            name=item['部门名称'],
            principal = item['负责人'],
            deputy_director = item['副主任'],
            department_code = item['部门编码'],
            tel = item['电话'],
            fax = item['传真'],
            address = item['地址'],
            postal_code = item['邮政编码'],
            email = item['电子邮件'],
            credit_limit = item['信用额度'],
            credit_rating =  item['信用等级'],
            credit_days = item['信用天数'],
            approval_number = item['批准文号'],
            approval_unit = item['批准单位'],
            department_attribute = item['部门属性'],
            incorporation_date = item['成立日期'],
            cancellation_date = item['撤销日期'],
            marks = item['备注'],
            department_english_name = item['部门英文名称'],
            department_full_name = item['部门全称'],
        )
        returnDict = {'code': 200, 'message': 'success'}

        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SuperSU_Pro(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "system_setup/SuperSU_Pro.html", {'realname': real_name, 'position': position, 'department': department,})


class UpdateHeadPortraitView(LoginRequiredMixin,View):
    def post(self, request):
        username = request.POST.get('username')  # 账户名
        HeadPortrait = request.FILES.get('HeadPortrait')  # 头像图片

        if not all([username, HeadPortrait]):
            returnDict = {'code': 400, 'message': '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        user_query_set = User.objects.filter(username=username)
        return_data = {
            'head_portrait':''
        }

        for user in user_query_set:
            user.head_portrait = HeadPortrait
            user.save()
            # 将图片转换为PNG
            cwd_path = os.getcwd()
            new_cwd_path = cwd_path.replace('\\','/')
            old_path = new_cwd_path+'/media/'+str(user.head_portrait)

            head_portrait_path = old_path.split('/media/')[-1]
            user.head_portrait = head_portrait_path
            user.save()

            return_data['head_portrait'] = '/media/'+str(user.head_portrait)
            request.user.head_portrait = user.head_portrait
        returnDict = {'code': 200, 'message': 'success','data':return_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class get_heard_pic(View):
    def post(self, request):
        head_portrait = "/media/" + str(request.user.head_portrait)
        if head_portrait == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait):
            head_portrait = "/static/personal_center/img/default.jpeg"

        inbox_obj = request.user.inboxinfopeople_set.filter(readed='unread', deleted='a', inbox_id__is_draft=False).order_by("-create_time")

        try:
            now_date_time = datetime.now().strftime("%Y-%m-%d")
            duty_obj = ThreePartyAttendanceInformation.objects.filter(job_number=request.user.job_number, duty_date=now_date_time)
            if duty_obj:
                morning_start = duty_obj.first().start_time
                morning_end = duty_obj.first().end_time
                afternoon_start = duty_obj.first().start_time1
                afternoon_end = duty_obj.first().end_time1
                check_in_one = duty_obj.first().checkininformation_set.filter(check_time__range=[now_date_time+" 00:00:00", now_date_time+" "+duty_obj.first().start_time])
                check_in_one_time = check_in_one.first().check_time.strftime("%Y-%m-%d %H:%M") if check_in_one.count() else ""

                datetime_obj = datetime.strptime(now_date_time+" "+morning_end, "%Y-%m-%d %H:%M")
                next_hour = datetime_obj + timedelta(hours=1)
                check_in_two = duty_obj.first().checkininformation_set.filter(check_time__range=[datetime_obj, next_hour])
                check_in_two_time = check_in_two.last().check_time.strftime("%Y-%m-%d %H:%M") if check_in_two.count() else ""

                afternoon_start_obj = datetime.strptime(now_date_time + " " + afternoon_start, "%Y-%m-%d %H:%M")
                afternoon_start_hour = afternoon_start_obj + timedelta(hours=-1)
                check_in_three = duty_obj.first().checkininformation_set.filter(check_time__range=[afternoon_start_hour, afternoon_start_obj])
                check_in_three_time = check_in_three.last().check_time.strftime("%Y-%m-%d %H:%M") if check_in_three.count() else ""

                afternoon_end_obj = datetime.strptime(now_date_time + " " + afternoon_end, "%Y-%m-%d %H:%M")
                check_in_four = duty_obj.first().checkininformation_set.filter(check_time__range=[afternoon_end_obj, now_date_time+" 23:59:59"])
                check_in_four_time = check_in_four.last().check_time.strftime("%Y-%m-%d %H:%M") if check_in_four.count() else ""
            else:
                morning_start = ""
                morning_end = ""
                afternoon_start = ""
                afternoon_end = ""
                check_in_one_time = ""
                check_in_two_time = ""
                check_in_three_time = ""
                check_in_four_time = ""
        except Exception as E:
            print("======================", E)
            morning_start = ""
            morning_end = ""
            afternoon_start = ""
            afternoon_end = ""
            check_in_one_time = ""
            check_in_two_time = ""
            check_in_three_time = ""
            check_in_four_time = ""
        try:
            clock_dic = {'morning_start': morning_start, "morning_end": morning_end, "afternoon_start": afternoon_start, "afternoon_end": afternoon_end,
                         "check_in_one_time": check_in_one_time, "check_in_two_time": check_in_two_time, "check_in_three_time": check_in_three_time, "check_in_four_time": check_in_four_time}

        except Exception as E:
            clock_dic = {"go_work_time": "", "off_work_time": "", 'morning_start': morning_start, "morning_end": morning_end, "afternoon_start": afternoon_start, "check_in_four_time": check_in_four_time,
                         "afternoon_end": afternoon_end, "check_in_one_time": check_in_one_time, "check_in_two_time": check_in_two_time, "check_in_three_time": check_in_three_time}

        read_aa, notic_flag = False, False

        notic_list = NoticePeople.objects.filter(state="accept", audit_people_id=request.user.id)

        for notic in notic_list:
            if Notice.objects.get(id=notic.notice_id_id).state == "end":
                notic_flag = True

        if inbox_obj.count():
            read_aa=True

        work_obj = request.user.check_work_current.all()

        approve_one, approve_two, one_count, two_count = 'false', 'false', 0, 0
        for work in work_obj:
            if work.state == "one":
                approve_one = 'true'
                one_count += 1
        rsk_obj = Company.objects.get(id=16).head_people
        if rsk_obj == request.user and CheckWorkTable.objects.filter(state="two"):
            approve_two = 'true'
            two_count += 1

        returnData = {"code": 200, "head_portrait": head_portrait, "read_aa": read_aa, "notic_flag": notic_flag, "clock_dic": clock_dic, "one_count": one_count, "approve_one": approve_one, "approve_two": approve_two, "two_count": two_count}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class permissions_validation(View):
    def post(self, request):
        permissions_type = request.POST.get("permissions_type", "新增审批")
        permissions_dict = GetGroupView(permissions_type, request.user)
        returnDict = {'code': 200, 'message': 'success', 'permissions': permissions_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class CustomerFormView(View):
    def get(self, request):
        objs = CustomerForm.objects.all()
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'objs': objs}

        return render(request, 'system_setup/UserDefinedWorksheet.html', context)


    def post(self, request):
        name = request.POST.get('name', '')
        business_html = request.POST.get('business_html', '')
        process_html = request.POST.get('process_html', '')
        process_json = request.POST.get('process_json', '')
        module = request.POST.get('module', '')
        module_obj = CustomerFormModule.objects.filter(name=module)
        if module_obj.count() == 0:
            CustomerFormModule.objects.create(name=module)
        CustomerForm.objects.create(apply_user=request.user, name=name, business_html=business_html,
                                    process_html=process_html, process_json=process_json, module=module)
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class CustomerFormDetailView(View):
    def get(self, request):
        id = request.GET.get('id')
        obj = CustomerForm.objects.get(id=int(id))
        record_list = deal_templates_html(obj.business_html)
        context = {'data': {'business_html': urllib.parse.unquote(base64.b64decode(obj.business_html).decode()),
                            'process_html': obj.process_html, "name": obj.name, "record_list": record_list,
                            "id": obj.id},
                   'realname': request.user.real_name,
                   'position': request.user.post,
                   'department': request.user.company.name,
                   'uuid': uuid.uuid1(),
                   }
        return render(request, 'system_setup/customer_form_detail.html', context)
        # return render(request, 'system_setup/customer_form_detail.html')


class LowCodeBillView(View):
    def post(self, request):
        user = request.user
        flow_id = request.POST.get('id', '')
        customer_form_id = request.POST.get('customer_form_id', '')
        data_html = request.POST.get('data_html', '')
        fj_number = request.POST.get('fj_number', '')
        CheckList = request.POST.get('CheckList', '')
        customer_form = CustomerForm.objects.get(id=int(customer_form_id))
        if flow_id:
            obj = LowCodeBill.objects.get(id=int(flow_id))
            obj.data_html=data_html
            obj.state='one'
            obj.lowcodebillauditrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
            obj.save()
        else:
            obj = LowCodeBill.objects.create(apply_user=user, customer_form=customer_form, data_html=data_html, fj_number=fj_number)

        if CheckList:
            obj.check_val = CheckList
            obj.save()

        if customer_form.old_flow == '1':
            audit_list = deal_process_html(json.loads(customer_form.process_json))
            for audit in audit_list:
                if audit['type'] == 'branch':
                    com = Company.objects.filter(name=audit['value']).first()
                    audit_people = com.head_people
                    LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                          audit_note='', node=audit['value'], seq=int(audit['num']))
                elif audit['type'] == 'staff':
                    fg = re.findall('\((.*?)\)', audit['value'])
                    audit_people = User.objects.filter(job_number=fg[0]).first()
                    LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                          audit_note='', node=audit['value'], seq=int(audit['num']))
                else:
                    if audit['value'] == '分管领导':
                        audit_people = user.company.leaders_id
                        LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
                    else:
                        com = user.company
                        audit_people = com.head_people
                        LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
            audits = obj.lowcodebillauditrecord_set.filter(seq=1)
            for audit in audits:
                obj.current_audit_users.add(audit.audit_people)
            returnDict = {'code': 200, 'message': '创建成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_list = new_flow_node(json.loads(customer_form.process_json))
            first_flag = True
            node_number = 1
            node_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'sever', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen',
                         14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty'}
            for node in audit_list:
                if node['node_type'] == '1':
                    if node['value'] == '科主任审核':
                        head_department = request.user.company.head_people
                    elif node['value'] == '申请人分管院长':
                        head_department = request.user.company.leaders_id
                    elif node['value'] == '书记审核':
                        head_department = Staffing.objects.get(station='书记').post_personnel.all().first()
                    else:
                        head_department = Staffing.objects.get(station='院长').post_personnel.all().first()
                    LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=head_department, audit_note='', node=node['value'], seq=int(node['num']))
                    if not obj.current_audit_users.all().count() and request.user != head_department and first_flag:
                        obj.current_audit_users.add(head_department)
                        first_flag = False

                elif node['node_type'] == '2':
                    audit_people = Company.objects.get(name=node['value']).head_people
                    LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people, audit_note='', node=node['value'], seq=int(node['num']))
                    if not obj.current_audit_users.all().count() and first_flag:
                        obj.current_audit_users.add(audit_people)
                        first_flag = False

                elif node['node_type'] == '3':
                    audit_people = Company.objects.get(name=node['value'].replace('分管院长', '')).leaders_id
                    LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people, audit_note='', node=node['value'], seq=int(node['num']))
                    if not obj.current_audit_users.all().count() and first_flag:
                        obj.current_audit_users.add(audit_people)
                        first_flag = False

                else:
                    audit_people_list = Staffing.objects.get(station=node['value']).post_personnel.all()
                    for audit_people in audit_people_list:
                        LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people, audit_note='', node=node['value'], seq=int(node['num']))
                        if first_flag:
                            obj.current_audit_users.add(audit_people)
                    first_flag = False

            returnDict = {'code': 200, 'message': '创建成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class LowCodeBillDetailView(View):
    def get(self, request):
        id = request.GET.get('id')
        obj = LowCodeBill.objects.get(id=int(id))
        audit_list = []
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number, file_type="0")]

        for audit_obj in obj.lowcodebillauditrecord_set.all().order_by('seq'):
            audit_list.append(
                {'audit_user': audit_obj.audit_people.real_name,
                 'state': audit_obj.get_state_display(),
                 'node': audit_obj.node,
                 'audit_note': audit_obj.audit_note,
                 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}
            )
        record_list = deal_templates_html(obj.customer_form.business_html)
        context = {
            'data': {'business_html': urllib.parse.unquote(base64.b64decode(obj.customer_form.business_html).decode()),
                     "name": obj.customer_form.name,
                     "data_html": obj.data_html, "audit_list": audit_list, "file_list": file_list,
                     "is_audit": 'true' if (request.user in obj.current_audit_users.all() and obj.state not in ['three','four']) else 'false',
                     "is_edit": 'true' if (request.user in obj.current_audit_users.all() and obj.state == 'four') else 'false',
                     "record_list": record_list,
                     "id": obj.id,
                     "uuid": obj.fj_number,
                     },
            'realname': request.user.real_name,
            'position': request.user.post,
            'department': request.user.company.name,
            }
        return render(request, 'system_setup/low_code_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = LowCodeBill.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        audit_record_obj = obj.lowcodebillauditrecord_set.filter(state='unaudit', audit_people=request.user).order_by(
            "seq").first()
        audit_record_obj.state = state
        audit_record_obj.audit_note = audit_note
        audit_record_obj.update_time = datetime.now()
        audit_record_obj.save()
        if state == 'audit':
            audit_record = obj.lowcodebillauditrecord_set.filter(state='unaudit', seq=audit_record_obj.seq)
            if audit_record.count() == 0:
                next_audit_record_objs = obj.lowcodebillauditrecord_set.filter(state='unaudit', seq=audit_record_obj.seq + 1)
                if next_audit_record_objs.count() == 0:
                    obj.state = 'two'
                    obj.save()
                    obj.current_audit_users.clear()
                else:
                    obj.current_audit_users.clear()
                    for next_audit_record_obj in next_audit_record_objs:
                        obj.current_audit_users.add(next_audit_record_obj.audit_people)
            else:
                obj.current_audit_users.remove(request.user)
        else:
            obj.state = 'four'
            obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(obj.apply_user)

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LowCodeBillWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        data_html = request.POST.get('data_html')
        obj = LowCodeBill.objects.get(id=int(id))
        obj.data_html = data_html
        obj.state = 'one'
        obj.save()
        audit_records = obj.lowcodebillauditrecord_set.all()
        for audit_record in audit_records:
            if audit_record.state != 'unaudit':
                LowCodeBillAuditRecord.objects.create(parent_id=obj, state='unaudit',
                                                      audit_people=audit_record.audit_people,
                                                      audit_note='', node=audit_record.node, seq=audit_record.seq)
        audits = obj.lowcodebillauditrecord_set.filter(seq=1, state='unaudit')
        for audit in audits:
            obj.current_audit_users.add(audit.audit_people)
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class UserDefind(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        # objs = CustomerForm.objects.all()
        return render(request, "system_setup/UserDefinedWorksheet.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = CustomerForm.objects.all().order_by(
            '-create_time')
        data_list = [{'id': obj.id,
                      # 'names': obj.names,
                      'apply_user': obj.apply_user.real_name,
                      'name': obj.name,
                      'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
                      'module': obj.module,
                      'abandoned': '已废弃' if obj.abandoned == '1' else "正常"
                      }
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OrderDefine(View):
    def get(self, request):
        return render(request, 'system_setup/order-define.html')


class admin_add(View):
    def get(self, request):
        objs = CustomerFormModule.objects.all()
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        role_obj = Staffing.objects.all()
        role_list = []
        for i in role_obj:
            role_list.append({"station": i.station})
        context = {"objs": objs, "company_list": company_list, "role_obj": role_list}
        return render(request, "system_setup/index.html", context)

# 下载excel文件
class download_excel(View):
    def get(self, request):
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="all_employees.xls"'
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('Available Items')
        row_num = 0
        font_style = xlwt.XFStyle()
        font_style.font.bold = True

        columns = ['姓名', '工号', '部门', '性别', '生日', '年龄', '转正时间', '手机', '职位', "学历", '民族', "身份证", "籍贯", "毕业院校", "专业", "政治面貌", "邮箱", 'QQ', '微信号']

        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)

        font_style = xlwt.XFStyle()

        rows = User.objects.filter(is_delete=0).values_list(
            'real_name', 'job_number', 'department', 'gender', 'birthday', 'age', 'regular_time', 'mobile', 'position', 'education', 'nation', "ID_number", "native_place", "graduated_university", "major",
        "political_outlook", 'mailbox', 'QQ', 'wechat_number')

        for row in rows:
            row_num += 1

            for col_num in range(len(row)):
                gender = str(row[col_num])
                if col_num == 3:
                    if gender == "male":
                        gender = "男"
                    else:
                        gender = "女"
                ws.write(row_num, col_num, gender, font_style)
        wb.save(response)

        return response

# 投票权限
class EnterVoting(View):
    def post(self, request):
        try:
            sta_obj = Staffing.objects.get(station="领导班子").post_personnel.all()
            flag, flag1 = 0, 0
            for obj in sta_obj:
                if request.user == obj:
                    flag = 1
                    break
            sta_obj1 = Staffing.objects.get(station="议题审核员").post_personnel.all()
            for obj1 in sta_obj1:
                if request.user == obj1:
                    flag1 = 1
                    break
            returnDict = {'code': 200, 'message': '', "flag": flag, 'flag1': flag1}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except:
            returnDict = {'code': 500, 'message': '领导班子角色未添加，请联系管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 新增医疗项目付款提交权限
class CheckJurisdiction(View):
    def post(self, request):
        CheckList = User.objects.filter(group_id__in=[4, 5])
        flag = 0
        for i in CheckList:
            if request.user == i:
                flag = 1
                break
        returnDict = {'code': 200, 'message': '', "flag": flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 检查是否是主任
class CheckDirector(View):
    def post(self, request):
        DirectorList = request.POST.get("DirectorList", "")
        travel_users = re.findall('\((.*?)\)', DirectorList)
        travel_users_objs = User.objects.filter(job_number__in=travel_users)
        flag = 0
        for i in travel_users_objs:
            if i.group.id in [2, 3, 4]:
                flag = 1
        returnDict = {'code': 200, 'message': '', "flag": flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 开始开会
class start_meeting(View):
    def post(self, request):
        topic_name = request.POST.get("topic_name", None)
        end_meeting = request.POST.get("end_meeting", None)
        operate_type = request.POST.get("operate_type", None)
        types = request.POST.get("types", None)
        meet_year = re.findall("(.*?)年", topic_name)[0]
        meet_number = re.findall("第(.*?)次", topic_name)[0]

        topic_obj = topic_meeting.objects.filter(topic_year=str(meet_year), meet_number=str(meet_number), topic_type=types.strip())

        if end_meeting and operate_type == '1':
            if ScanCode.objects.filter(type='1' if types.strip() == 'yb' else '2', topic_year=str(meet_year), meet_number=str(meet_number)):
                CodeObj = ScanCode.objects.filter(type='1' if types.strip() == 'yb' else '2', topic_year=str(meet_year), meet_number=str(meet_number)).first()
                CodeObj.whether_scan = "1"
                CodeObj.save()
            for top_obj in topic_obj:
                top_obj.MeetingStatus = 'ending'
                top_obj.save()
        elif end_meeting and operate_type == '2':
            for top_obj in topic_obj:
                VoteLeader.objects.filter(topics_id=top_obj).delete()
                top_obj.topic.state = 'unmetting'
                top_obj.topic.is_meeting = 'a'
                top_obj.topic.meetings_num = '0'
                top_obj.topic.save()
            topic_obj.delete()
            returnDict = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            for top_obj in topic_obj:
                top_obj.state = 'voting'
                top_obj.save()

            # meet_count = 0
            # for ii in leader_dict:
            #     if leader_dict[ii]['meetornot']:
            #         meet_count += 1
            # if meet_count/9 < 2/3:
            #     returnDict = {'code': 400, 'message': '参会人员未达到三分之二，不能开始会议！'}
            #     return HttpResponse(json.dumps(returnDict), content_type="application/json")


            #     for i in leader_dict:
            #         if leader_dict[i]['meetornot']:
            #             VoteLeader.objects.create(leaders=User.objects.get(job_number=i), topics_id=top_obj, meet_number=meet_number, topic_year=meet_year,
            #                                       vote=leader_dict[i]['voteornot'], Participation=leader_dict[i]['meetornot'], host=leader_dict[i]['hostornot'])
            #         else:
            #             VoteLeader.objects.create(leaders=User.objects.get(job_number=i), topics_id=top_obj, meet_number=meet_number, topic_year=meet_year,
            #                                       vote=leader_dict[i]['voteornot'], Participation=leader_dict[i]['meetornot'], host=leader_dict[i]['hostornot'], reason=meeting_reason)

        returnDict = {'code': 200, 'message': '', "types": types.strip()}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 移除参会领导
class remove_leader(View):
    def post(self, request):
        topic_name = request.POST.get("topic_name", None)
        leaders = request.POST.get("leaders", None)
        types = request.POST.get("types", None)
        meeting_reason1 = request.POST.get("meeting_reason1", None)
        meet_year = re.findall("(.*?)年", topic_name)[0]
        meet_number = re.findall("第(.*?)次", topic_name)[0]

        topic_obj = topic_meeting.objects.filter(topic_year=meet_year, meet_number=meet_number)
        if types == 'add':
            for top_obj in topic_obj:
                leader_obj = top_obj.voteleader_set.filter(leaders=User.objects.get(job_number=int(leaders))).first()
                leader_obj.vote = True
                leader_obj.Participation = True
                leader_obj.departure_reason = leader_obj.departure_reason+"&&"+meeting_reason1
                leader_obj.save()
        else:
            for top_obj in topic_obj:
                leader_user = User.objects.get(job_number=int(leaders))
                if top_obj.voteleader_set.filter(leaders=leader_user, state="voting"):
                    leader_obj = top_obj.voteleader_set.filter(leaders=User.objects.get(job_number=int(leaders)), state="voting").first()
                    leader_obj.vote = False
                    leader_obj.Participation = False
                    leader_obj.departure_reason = meeting_reason1
                    leader_obj.save()
        returnDict = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class AuthorityConfirm(View):
    def post(self, request):
        types = request.POST.get("types", '1')
        if types == '1':
            BGS_appave1 = Staffing.objects.get(station='外出干部审核员').post_personnel.all()

            flag = 'false'
            for i in BGS_appave1:
                if request.user == i:
                    flag = 'true'
            if request.user.group.id in [1, 2] or request.user.company.id in [80, 16]:
                flag = 'true'

            returnDict = {'code': 200, 'message': '', 'flag': flag}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            flag = 'false'
            bgs_obj = Staffing.objects.get(station='办公室').post_personnel.all()
            if request.user in bgs_obj:
                flag = 'true'
            returnDict = {'code': 200, 'message': '', 'flag': flag}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class document_confirm(View):
    def post(self, request):
        BGS_appave1 = Company.objects.filter(id__in=[3, 80])

        flag = 'false'
        for i in BGS_appave1:
            if request.user.company == i:
                flag = 'true'

        if request.user.group.id in [1, 2]:
            flag = 'true'

        returnDict = {'code': 200, 'message': '', 'flag': flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DeleteFlow(View):
    def post(self, request):
        tar_id = request.POST.get("id", None)
        obj = TravelReimbursement.objects.get(id=int(tar_id))
        obj.audit_users_already.remove(request.user)
        obj.save()
        returnDict = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MeetingPermissions(View):
    def post(self, request):
        meet_flag = 'false'
        meet_obj = topic_meeting.objects.filter(MeetingStatus='progress')
        if meet_obj.count():
            if meet_obj.first().topic_type == 'yb':
                meet_people_obj = Staffing.objects.get(station='开会按钮可见').post_personnel.all()
                if request.user in meet_people_obj:
                    meet_flag = 'true'
            else:
                if request.user.company.id in [3, 80, 87] or request.user.group.id in [1, 2]:
                    meet_flag = 'true'

        AttendedObj = AttendedMeeting.objects.filter(status='progress')
        if AttendedObj.count():
            expert_obj = AttendedObj.first().topic.expert_database.expertpeople_set.all() if AttendedObj.first().topic.expert_database else []
            director_obj = AttendedObj.first().committee_name.chairman.all()
            deputy_director_obj = AttendedObj.first().committee_name.vice_chairman.all()
            liaison_obj = AttendedObj.first().committee_name.liaison_officer.real_name
            expert_list = [i.name for i in expert_obj]
            director_list = [i.real_name for i in director_obj]
            deputy_director_list = [i.real_name for i in deputy_director_obj]
            expert_list.append(liaison_obj)
            all_data = list(set(expert_list + director_list + deputy_director_list))
            if request.user.real_name in all_data:
                meet_flag = 'true'
        returnDict = {'code': 200, 'message': '查询成功！', 'meet_flag': meet_flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UploadExcel(View):
    def post(self, request):
        files = request.FILES.get('file')                      # 正文
        types = request.POST.get('types', None)
        type_file = files.name.split('.')[-1]
        if type_file not in ['xlsx', 'xls']:
            return HttpResponse(json.dumps({"code": 400, 'message': "请上传excel文件！"}))
        read_file = xlrd.open_workbook(filename=None, file_contents=files.read())
        file_table = read_file.sheets()[0]
        file_table_rows = file_table.nrows
        peoples_list = []
        # 读表格数据，从第二行开始，一般第一行都是说明
        try:
            for i in range(1, file_table_rows):
                a = file_table.cell(i, 0)
                peoples_list.append(int(a.value))
        except:
            pass
        if types == 'new_add':
            names = request.POST.get('name', None)
            packet = "".join([i[0][0] for i in pinyin(names)]).upper()
            function_obj = Function.objects.create(packet=packet, describe=names)
            try:
                for user_obj in User.objects.filter(job_number__in=peoples_list):
                    user_obj.function_ids.add(function_obj)
            except Exception as e:
                print("E: ", e)
            return HttpResponse(json.dumps({"code": 200, 'message': "分组添加成功！"}))
        elif types in ['check_work', 'labor_dispatch']:
            work_month = request.POST.get('month', None)
            work_yesr = request.POST.get('year', None)
            gauge_outfit = file_table.cell(0, 0).value.strip()
            my_director = request.user.company.head_people
            if types == 'check_work':
                WorkType = '1'
                try:
                    CheckObj = request.user.checkworktable_set.get(company=request.user.company, work_month=work_month, work_yesr=work_yesr, WorkType='1')
                    if CheckObj:
                        CheckObj.checkworkrecord_set.all().delete()
                        CheckObj.checkworkattendance_set.all().delete()
                        CheckObj.current_audit_users.clear()
                        CheckObj.audit_users_already.clear()
                        CheckObj.delete()
                except:
                    pass
            else:
                WorkType = '2'
                try:
                    CheckObj = request.user.checkworktable_set.get(company=request.user.company, work_month=work_month, work_yesr=work_yesr, WorkType='2')
                    if CheckObj:
                        CheckObj.checkworkrecord_set.all().delete()
                        CheckObj.checkworkattendance_set.all().delete()
                        CheckObj.current_audit_users.clear()
                        CheckObj.audit_users_already.clear()
                        CheckObj.delete()
                except:
                    pass

            obj = CheckWorkTable.objects.create(apply_user=request.user, company=request.user.company, gauge_outfit=gauge_outfit, work_month=work_month, work_yesr=work_yesr, WorkType=WorkType)

            SupportCenter = Staffing.objects.get(station='支助中心').post_personnel.all().first()

            if request.user == SupportCenter:
                obj.audit_users_already.add(request.user)
                obj.state = "two"
                CheckWorkRecord.objects.create(parent_id=obj, state="audit", audit_people=request.user, node="one")
            else:
                if request.user != my_director:
                    if request.user in request.user.company.deputy_director_ids.all():
                        obj.audit_users_already.add(request.user)
                        obj.state = "two"
                        CheckWorkRecord.objects.create(parent_id=obj, state="audit", audit_people=request.user, node="one")
                    elif request.user == request.user.company.head_nurse_id:
                        obj.audit_users_already.add(request.user)
                        obj.state = "two"
                        CheckWorkRecord.objects.create(parent_id=obj, state="audit", audit_people=request.user, node="one")
                    else:
                        obj.state = "one"
                        obj.current_audit_users.add(my_director)
                        CheckWorkRecord.objects.create(parent_id=obj, state="unaudit", audit_people=my_director, node="one")
                        for iii in request.user.company.deputy_director_ids.all():
                            obj.current_audit_users.add(iii)
                            CheckWorkRecord.objects.create(parent_id=obj, state="unaudit", audit_people=iii, node="one")
                        if request.user.company.head_nurse_id:
                            obj.current_audit_users.add(request.user.company.head_nurse_id)
                            CheckWorkRecord.objects.create(parent_id=obj, state="unaudit", audit_people=request.user.company.head_nurse_id, node="one")
                else:
                    obj.audit_users_already.add(request.user)
                    obj.state = "two"
                    CheckWorkRecord.objects.create(parent_id=obj, state="audit", audit_people=request.user, node="one")

            obj.save()
            if types == 'check_work':
                for t in range(4, file_table_rows):
                    try:
                        try:
                            tijiao_people = User.objects.get(job_number=int(file_table.cell(t, 2).value))
                        except Exception as E:
                            obj.checkworkrecord_set.all().delete()
                            obj.delete()
                            if "invalid literal" in str(E):
                                return HttpResponse(json.dumps({"code": 400, 'message': f"上传失败！请下载模板重新上传！"}))
                            return HttpResponse(json.dumps({"code": 400, 'message': f"'{file_table.cell(t, 4).value}' 该人员未在系统中，请联系管理员添加！"}))
                        CheckWorkAttendance.objects.create(
                            attendance=obj,
                            serial=int(file_table.cell(t, 0).value) if type(file_table.cell(t, 0).value) is float else file_table.cell(t, 0).value,
                            department=file_table.cell(t, 1).value,
                            job_number=int(file_table.cell(t, 2).value) if type(file_table.cell(t, 2).value) is float else file_table.cell(t, 2).value,
                            practice=int(file_table.cell(t, 3).value) if type(file_table.cell(t, 3).value) is float else file_table.cell(t, 3).value,
                            name=int(file_table.cell(t, 4).value) if type(file_table.cell(t, 4).value) is float else file_table.cell(t, 4).value,
                            attendance_days=int(file_table.cell(t, 5).value) if type(file_table.cell(t, 5).value) is float else file_table.cell(t, 5).value,
                            work_days=int(file_table.cell(t, 6).value) if type(file_table.cell(t, 6).value) is float else file_table.cell(t, 6).value,
                            aid_jing=int(file_table.cell(t, 7).value) if type(file_table.cell(t, 7).value) is float else file_table.cell(t, 7).value,
                            quarantine=int(file_table.cell(t, 8).value) if type(file_table.cell(t, 8).value) is float else file_table.cell(t, 8).value,
                            heterodyne=int(file_table.cell(t, 9).value) if type(file_table.cell(t, 9).value) is float else file_table.cell(t, 9).value,
                            education=int(file_table.cell(t, 10).value) if type(file_table.cell(t, 10).value) is float else file_table.cell(t, 10).value,
                            planning=int(file_table.cell(t, 11).value) if type(file_table.cell(t, 11).value) is float else file_table.cell(t, 11).value,
                            maternity=int(file_table.cell(t, 12).value) if type(file_table.cell(t, 12).value) is float else file_table.cell(t, 12).value,
                            annual=int(file_table.cell(t, 13).value) if type(file_table.cell(t, 13).value) is float else file_table.cell(t, 13).value,
                            absence=int(file_table.cell(t, 14).value) if type(file_table.cell(t, 14).value) is float else file_table.cell(t, 14).value,
                            sick=int(file_table.cell(t, 15).value) if type(file_table.cell(t, 15).value) is float else file_table.cell(t, 15).value,
                            industrial=int(file_table.cell(t, 16).value) if type(file_table.cell(t, 16).value) is float else file_table.cell(t, 16).value,
                            visit=int(file_table.cell(t, 17).value) if type(file_table.cell(t, 17).value) is float else file_table.cell(t, 17).value,
                            marriage=int(file_table.cell(t, 18).value) if type(file_table.cell(t, 18).value) is float else file_table.cell(t, 18).value,
                            bereavement=int(file_table.cell(t, 19).value) if type(file_table.cell(t, 19).value) is float else file_table.cell(t, 19).value,
                            vacation=int(file_table.cell(t, 20).value) if type(file_table.cell(t, 20).value) is float else file_table.cell(t, 20).value,
                            parental_leave=int(file_table.cell(t, 21).value) if type(file_table.cell(t, 21).value) is float else file_table.cell(t, 21).value,
                            notes=int(file_table.cell(t, 22).value) if type(file_table.cell(t, 22).value) is float else file_table.cell(t, 22).value,
                            apply_user=tijiao_people
                        )
                    except Exception as E:
                        print("==============================", E)
                        obj.checkworkrecord_set.all().delete()
                        obj.delete()
                        return HttpResponse(json.dumps({"code": 400, 'message': "上传失败！请下载模板重新上传！"}))

            else:
                for t in range(3, file_table_rows):
                    try:
                        CheckWorkLaborDispatch.objects.create(
                            attendance=obj,
                            serial=int(file_table.cell(t, 0).value) if type(file_table.cell(t, 0).value) is float else file_table.cell(t, 0).value,
                            department=file_table.cell(t, 1).value if file_table.cell(t, 1).value else '',
                            project_name=file_table.cell(t, 2).value,
                            attendance_days=int(file_table.cell(t, 3).value) if type(file_table.cell(t, 3).value) is float else file_table.cell(t, 3).value,
                            leave_type=int(file_table.cell(t, 4).value) if type(file_table.cell(t, 4).value) is float else file_table.cell(t, 4).value,
                            labor_discipline=int(file_table.cell(t, 5).value) if type(file_table.cell(t, 5).value) is float else file_table.cell(t, 5).value,
                            work_quality=int(file_table.cell(t, 6).value) if type(file_table.cell(t, 6).value) is float else file_table.cell(t, 6).value,
                            working_ability=int(file_table.cell(t, 7).value) if type(file_table.cell(t, 7).value) is float else file_table.cell(t, 7).value,
                            other=int(file_table.cell(t, 8).value) if type(file_table.cell(t, 8).value) is float else file_table.cell(t, 8).value,
                            total_score=int(file_table.cell(t, 9).value) if type(file_table.cell(t, 9).value) is float else file_table.cell(t, 9).value,
                            notes=int(file_table.cell(t, 10).value) if type(file_table.cell(t, 10).value) is float else file_table.cell(t, 10).value
                        )
                    except Exception as E:
                        print("++++++++++++++++", E)
                        obj.checkworkrecord_set.all().delete()
                        obj.delete()
                        return HttpResponse(json.dumps({"code": 400, 'message': "上传失败！请下载最新模板重新上传！"}))

            me_head = request.user.company.head_people
            if me_head == request.user:
                pass
            return HttpResponse(json.dumps({"code": 200, 'message': "上传成功！", "data": ", ".join([i.real_name for i in obj.current_audit_users.all()])}))

        else:
            group_id = request.POST.get('group_id', None)
            function_obj = Function.objects.get(id=group_id)
            # 删除现有小组人员
            function_obj.function_ids_users.clear()
            for user_obj in User.objects.filter(job_number__in=list(set(peoples_list))):
                user_obj.function_ids.add(function_obj)
            returnData = {'code': 200, 'message': '更新成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

class QueryAuthorization(View):
    def post(self, request):
        checked_value = request.POST.get('checked_value', None)
        category_list = []
        repeat_list = []
        for i in json.loads(checked_value):
            category_obj = request.user.quickauthorizationapplicationcategory_set.filter(seal_id=seal.objects.get(seal_name=i))
            for jj in category_obj:
                if jj.category not in repeat_list:
                    category_list.append({"id": jj.id, "category": jj.category})
                    repeat_list.append(jj.category)

        returnData = {'code': 200, 'message': '查询成功！', "data": category_list}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class PrintingIssues(View):
    def post(self, request):
        types = request.POST.get('types', "")
        meet_flag = 'false'
        bgs_obj = Staffing.objects.get(station='办公室').post_personnel.all()
        if request.user in bgs_obj:
            meet_flag = 'true'

        if types == "3" and request.user.company.id in [3, 80]:
            meet_flag = 'true'

        caiwu_kuaiji = Staffing.objects.get(station='财务出纳').post_personnel.all()
        if types == "3" and request.user in caiwu_kuaiji:
            meet_flag = 'true'

        try:
            jjhthq_obj = Staffing.objects.get(station='合同会签报表').post_personnel.all()
            if types == "2" and request.user in jjhthq_obj:
                meet_flag = 'true'
        except:
            pass
        chailv_shenqing = Staffing.objects.get(station='差旅申请报表').post_personnel.all()
        if types == "4" and request.user in chailv_shenqing:
            meet_flag = 'true'

        returnDict = {'code': 200, 'message': '查询成功！', 'flag': meet_flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SignaturePersonnel(View):
    def post(self, request):
        ids = request.POST.get("id", '')
        types = request.POST.get("types", '')
        if ids:
            obj = CheckWorkTable.objects.get(id=int(ids))
            obj.audit_users_already.add(request.user)
            if obj.state == "one":
                obj.current_audit_users.clear()
                one_obj = obj.checkworkrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                one_obj.state = 'audit'
                one_obj.update_time = datetime.now()
                obj.state = "two"
                one_obj.save()
                obj.save()
                obj.checkworkrecord_set.filter(node='one', state='unaudit').delete()
        else:
            CheckWorkTable.objects.filter(whether_verify="0", WorkType=types).update(whether_verify="1", state="end")
        returnDict = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ExportData(View):
    def post(self, request):
        types = request.POST.get("types", '')                   # 下载类型：汇总下载，部门下载
        year = request.POST.get("year", datetime.now().year)
        month = request.POST.get("month", datetime.now().month)
        dept = request.POST.get("dept", '')
        DownLoadType = request.POST.get("DownLoadType", '')

        if DownLoadType == "1":
            last_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], WorkType='1').last()
            if not dept:
                check_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], work_month=str(last_obj.work_month), work_yesr=str(last_obj.work_yesr), WorkType='1')
                attendance_list = []
                for i in check_obj:
                    attendance_list.append(i.id)
                AttendanceObj = CheckWorkAttendance.objects.filter(attendance__in=attendance_list)
                gauge_outfit = check_obj.first().gauge_outfit
            else:
                AttendanceObj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_month=str(last_obj.work_month), attendance__work_yesr=str(last_obj.work_yesr), attendance__WorkType='1', department=dept)
                gauge_outfit = AttendanceObj.first().attendance.gauge_outfit

            AttendanceList = []
            for i in AttendanceObj:
                AttendanceList.append([
                    i.serial, i.department, i.job_number, i.practice, i.name, i.attendance_days, i.work_days,
                    i.aid_jing, i.quarantine, i.heterodyne,
                    i.education, i.planning, i.maternity, i.annual, i.absence, i.sick, i.industrial, i.visit,
                    i.marriage, i.bereavement, i.vacation,
                    i.parental_leave, i.notes
                ])

            file_path = attendance_sheet().create_excel(AttendanceList, gauge_outfit)

            returnDict = {'code': 200, 'message': '操作成功！', "data": {"file_path": file_path}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
           # print("===============", month)
            if month != '0':
                last_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], WorkType='2', work_month=month, work_yesr=year).last()
            else:
                last_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], WorkType='2', work_yesr=year).last()
            check_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], work_month=str(last_obj.work_month), work_yesr=str(last_obj.work_yesr), WorkType='2')
            attendance_list = []
            for i in check_obj:
                attendance_list.append(i.id)
            AttendanceObj = CheckWorkLaborDispatch.objects.filter(attendance__in=attendance_list)
            gauge_outfit = check_obj.first().gauge_outfit

            AttendanceList = []
            for i in AttendanceObj:
                AttendanceList.append([
                    i.serial, i.department, i.project_name, i.attendance_days, i.leave_type, i.labor_discipline,
                    i.work_quality, i.working_ability, i.other, i.total_score, i.notes
                ])

            file_path = attendance_sheet().dispatch_excel(AttendanceList, gauge_outfit)

            returnDict = {'code': 200, 'message': '操作成功！', "data": {"file_path": file_path}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")



class shelve_flow(View):
    def post(self, request):
        ids = request.POST.get("id", '')
        database_name = request.POST.get("database_name", '')
        appave_opinion = request.POST.get("appave_opinion", '')
        if database_name == '1':
            database_name = OfficialDocuments
        elif database_name == '2':
            database_name = Notice
        elif database_name == '3':
            database_name = VehicleApply
        elif database_name == '4':
            database_name = Topics
        elif database_name == '5':
            database_name = ConferenceMemo
        elif database_name == '6':
            database_name = ConferenceRoomApplication
        elif database_name == '7':
            database_name = GatheringApply
        elif database_name == '8':
            database_name = EvaluationOfMedicalEthics
        elif database_name == '9':
            database_name = SealApply
        elif database_name == '10':
            database_name = FixedAssets
        elif database_name == '11':
            database_name = TravelApply
        elif database_name == '12':
            database_name = TravelReimbursement
        elif database_name == '13':
            database_name = BusinessContract
        elif database_name == '14':
            database_name = MedicalMaterials
        elif database_name == '15':
            database_name = LogisticsOffice
        elif database_name == '16':
            database_name = NutritionalMeals
        elif database_name == '17':
            database_name = GeneralFinance
        elif database_name == '18':
            database_name = LeaveRequest
        elif database_name == '19':
            database_name = Dimission
        elif database_name == '20':
            database_name = NewMedicalServices
        elif database_name == '21':
            database_name = SurgicalGrading
        elif database_name == '22':
            database_name = SoloPracticeApply
        elif database_name == '23':
            database_name = OutgoingCadresData
        elif database_name == '24':
            database_name = LaborUnionExpenses
        elif database_name == '25':
            database_name = SealMaking
        elif database_name == '26':
            database_name = SubjectFunding
        elif database_name == '27':
            database_name = QuickAuthorization
        elif database_name == '28':
            database_name = BookSubscription
        elif database_name == '29':
            database_name = PartyBuilding
        elif database_name == '30':
            database_name = LowCodeBill
        else:
            database_name = ''

        obj = database_name.objects.get(id=int(ids))
        obj_set = obj.sealapplyauditrecord_set.filter(state='unaudit', audit_people=request.user).first()
        obj_set.update_time = datetime.now()
        obj_set.state = 'shelve'
        obj_set.audit_note = appave_opinion
        obj.last_state = obj.state
        obj.state = 'shelve'
        obj.save()
        obj_set.save()
        returnDict = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class reduction(View):
    def post(self, request):
        ids = request.POST.get("id", '')
        obj = SealApply.objects.get(id=int(ids))
        obj.state = obj.last_state
        obj.last_state = ""
        obj.save()

        try:
            RecordObj = SealApplyAuditRecord.objects.filter(parent_id=obj, audit_people=request.user, state='shelve').first()
            SealApplyAuditRecord.objects.create(parent_id=obj, audit_people=request.user, audit_note="", state='unaudit', node=RecordObj.node)
            returnDict = {'status': 'success', 'message': '操作成功！', 'code': 200}
        except Exception as E:
            print(E)
            returnDict = {'status': 'success', 'message': '还原失败！', 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TraBusApi(View):
    def post(self, request):
        flag = 'false'
        bill_obj = BillGroup.objects.get(id=34).executor.all()
        if request.user in bill_obj:
            flag = 'true'
        returnDict = {'code': 200, 'message': '查询成功！', 'flag': flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class add_empower(View):
    def post(self, request):
        detail_json = request.POST.get("detail_json", '')                                 # 授权详情
        # conferee = request.POST.get("conferee", '')                                           # 经办人
        authorization_type = request.POST.get("authorization_type", '')                     # 授权类型
        department = request.POST.get("department", '')                                     # 授权科室
        take_effect_time = request.POST.get("take_effect_time", '')                         # 生效时间
        lose_efficacy_time = request.POST.get("lose_efficacy_time", '')                     # 失效时间
        select_leader = request.POST.get("select_leader", '')                               # 分管领导
        flow_id = request.POST.get("id", '')                                                # 流程ID

        if not department:
            returnDict = {'code': 400, 'message': '请选择授权部门！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if not flow_id:
            obj = QuickAuthorizationSeal.objects.create(detail_json=detail_json, company=Company.objects.get(id=int(department)), audit_people=request.user,
                                                  authorization_type=authorization_type, take_effect_time=take_effect_time, lose_efficacy_time=lose_efficacy_time,
                                                        select_leader=User.objects.get(id=int(select_leader)))
        else:
            obj = QuickAuthorizationSeal.objects.get(id=int(flow_id))
            obj.detail_json = detail_json
            obj.company = Company.objects.get(id=int(department))
            obj.authorization_type = authorization_type
            obj.take_effect_time = take_effect_time
            obj.lose_efficacy_time = lose_efficacy_time
            obj.select_leader = User.objects.get(id=int(select_leader))
            obj.save()

        obj.quickauthorizationapplicationcategory_set.all().delete()
        for i in json.loads(detail_json):
            seal_obj = seal.objects.get(id=i['yinzhang'])
            for j in i['neirong']:
                QuickAuthorizationApplicationCategory.objects.create(seal_id=seal_obj, authorized_person=User.objects.get(job_number=re.findall("\((.*?)\)", j["HandledBy"])[0]),
                                                                     category=j['neirong'], quick=obj, level=j["type"])
        returnDict = {'code': 200, 'message': '添加成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class can_modify(View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过

        obj = SealApply.objects.get(id=int(id))
        audit_record_list = request.user.sealapplyauditrecord_set.filter(parent_id=obj)
        for i in audit_record_list:
            i.update_time = datetime.now()
            i.state = state
            i.audit_note = audit_note
            i.save()
            if state == "draft":
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)
                obj.state = "six"
                obj.save()

        returnDict = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class download_file(View):
    def get(self, request):
        file_path = request.GET.get("file_path")
        file_name = os.path.basename(file_path)
        if os.path.exists(file_path):
            with open(file_path, 'rb') as f:
                file_data = f.read()
            response = HttpResponse(file_data, content_type='application/octet-stream')
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(file_name))
            return response
        else:
            return HttpResponse("Sorry, the file you requested does not exist.")

class download_topic_file(View):
    def get(self, request):
        filePath = request.GET.get("file_path")
        FilePath = os.getcwd() + filePath
        file_name = os.path.basename(FilePath)
        if not os.path.isfile(FilePath):  # 判断下载文件是否存在
            return HttpResponse("Sorry but Not Found the File")

        def file_iterator(file_path, chunk_size=512):
            """
            文件生成器,防止文件过大，导致内存溢出
            :param file_path: 文件绝对路径
            :param chunk_size: 块大小
            :return: 生成器
            """
            with open(file_path, mode='rb') as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break

        try:
            # 设置响应头
            # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
            response = StreamingHttpResponse(file_iterator(FilePath))
            # 以流的形式下载文件,这样可以实现任意格式的文件下载
            response['Content-Type'] = 'application/octet-stream'
            # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
            response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
        except:
            return HttpResponse("Sorry but Not Found the File")

        return response

class get_scheduling(View):
    def post(self, request):
        now = datetime.now()
        if 6 > now.weekday():
            day = 6 - now.weekday()
            sunday = now + timedelta(days=day)
        else:
            sunday = now
        if now.weekday() > 0:
            day = now.weekday()
            monday = now + timedelta(days=-day)
        else:
            monday = now
        two_line = [{'name': record.user.real_name, 'duty_date': record.date.strftime("%Y-%m-%d"),
                     'week': num_to_char(record.date.weekday() + 1)} for record in
                    SortLine.objects.filter(is_deleted=False, type='2', date__range=[monday, sunday])]
        one_line = [
            {'name': record.user.real_name, 'phone': record.user.mobile, 'type': record.get_day_type_display(),
             'duty_date': record.date.strftime("%Y-%m-%d"),
             'week': num_to_char(record.date.weekday() + 1)} for record in
            SortLine.objects.filter(is_deleted=False, type='1', date__range=[monday, sunday])]
        one_line_dict = {}
        for jj in one_line:
            if jj["duty_date"] in one_line_dict:
                one_line_dict[jj["duty_date"]].append(jj)
            else:
                one_line_dict[jj["duty_date"]] = [jj]

        two_line_dict = {}
        for tt in two_line:
            if tt["duty_date"] in two_line_dict:
                two_line_dict[tt["duty_date"]].append(tt)
            else:
                two_line_dict[tt["duty_date"]] = [tt]

        all_dict = {'one_line': one_line_dict, 'two_line': two_line_dict,
                    'today': time.strftime("%Y-%m-%d", time.localtime())}
        returnDict = {'code': 200, 'message': '获取成功！', "all_dict": all_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class my_to_do_list(View):
    def post(self, request):
        daiban_data = manage_flow().audit_post(request.user.id, request.user.real_name)
        for i in daiban_data:
            if "议题" in i["types"] and "委员" not in i["types"]:
                i["url"] = "Issue_modify.html?id=" + i["id"] if i["node"] == "退回" else "SubjectDetailst.html?id=" + i["id"]
        returnDict = {'code': 200, 'message': '获取成功！', "daiban_list": daiban_data[:5]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class notice_announcement(View):
    def post(self, request):
        notic_list = NoticePeople.objects.filter(audit_people=request.user, notice_id__state='audit').order_by("-create_time")
        notic_dict_list = []
        for i in notic_list[:2]:
            notic_dict_list.append({"id": i.notice_id.id, "name": i.notice_id.name, "create_time": i.notice_id.create_time.strftime("%Y-%m-%d %H:%M")})
        returnDict = {'code': 200, 'message': '获取成功！', "notic_list": notic_dict_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class my_receipt(View):
    def post(self, request):
        # 我的收文
        q1 = OfficialDocumentsPeople.objects.filter(state='accepted', audit_people=request.user).order_by(
            "-update_time")
        a2 = ConferenceMemoPeople.objects.filter(state='accepted', audit_people=request.user).order_by(
            "-update_time")
        inbox = sorted(chain(q1, a2), key=attrgetter('update_time'), reverse=True)
        data_list = []
        for i in inbox[:5]:
            try:
                aaa = i.real_name
                title = i.notice_id.conference_memo_text
                document_number = i.notice_id.document_number
                doc_url = "document_detail.html?attention=1&id=" + str(i.notice_id.id)
                if i.notice_id.drafter:
                    real_name = i.notice_id.drafter
                    department = i.notice_id.drafter_company
                else:
                    real_name = i.notice_id.apply_user.real_name
                    department = i.notice_id.apply_user.department
            except:
                title = i.notice_id.title
                document_number = i.notice_id.recive_number
                real_name = i.notice_id.apply_user.real_name
                department = i.notice_id.apply_user.department
                doc_url = "examinationDetail.html?id=" + str(i.notice_id.id)
            one_dict = {'id': i.notice_id.id, "title": title, "real_name": real_name, "department": department,
                        "create_time": i.update_time.strftime("%Y-%m-%d %H:%M"), "document_number": document_number,
                        'url': doc_url}
            data_list.append(one_dict)
        returnDict = {'code': 200, 'message': '获取成功！', "data_list": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class my_mail(View):
    def post(self, request):
        inbox_obj = request.user.inboxinfopeople_set.filter(deleted='a', inbox_id__is_draft=False).order_by("-create_time")
        inbox_li = []

        for i in inbox_obj:
            item = {}
            item['message_id'] = i.inbox_id.id
            item['sender_name'] = i.inbox_id.proposer.real_name
            item['sender'] = i.inbox_id.proposer.job_number
            item['title'] = i.inbox_id.title
            item['read'] = 'true' if i.readed == "read" else 'false'
            item['create_time'] = i.inbox_id.create_time.strftime("%Y-%m-%d %H:%M")
            inbox_li.append(item)
        returnDict = {'code': 200, 'message': '获取成功！', "inbox_li": inbox_li[:5]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class GetNext(View):
    def post(self, request):
        get_type = request.POST.get("get_type", '')
        seal_id = request.POST.get("id", '')
        if get_type == 'below':
            obj = SealApply.objects.filter(state='five', number__gt=SealApply.objects.get(id=int(seal_id)).number).order_by("number")
            mess_str = "没有下一个了！"
        else:
            obj = SealApply.objects.filter(state='five', number__lt=SealApply.objects.get(id=int(seal_id)).number).order_by("-number")
            mess_str = "没有上一个了！"

        if obj:
            returnDict = {'code': 200, 'message': '获取成功！', "id": obj.first().id}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 400, 'message': mess_str, "id": ''}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PrintDirectory(View):
    def post(self, request):
        print_type = request.POST.get("print_type", '')
        data_list = request.POST.get("data_list", '')
        dir_title = request.POST.get("dir_title", '')
        if print_type == 'YB_mulu':
            file_path = create_excel(json.loads(data_list), dir_title)
        elif print_type == 'DB_mulu':
            file_path = create_excel(json.loads(data_list), dir_title)
        else:
            file_path = create_excel(json.loads(data_list), dir_title)
        returnDict = {'code': 200, 'message': '获取成功！', "data": [{"file_path": file_path}]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyAuthority(View):
    def post(self, request):
        obj1 = Staffing.objects.get(station='支委').post_personnel.all()
        obj2 = Staffing.objects.get(station='支部书记').post_personnel.all()
        flag = 'false'
        BranchCommittee = obj1 | obj2
        if request.user in BranchCommittee:
            flag = 'true'
        returnDict = {'code': 200, 'message': '查询成功！', 'flag': flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class select_user_data(View):
    def post(self, request):
        user_id = request.POST.get("id", '')
        user_obj = User.objects.get(id=int(user_id))
        if user_obj.signature_picture:
            signature_picture_url = '/media/' + str(user_obj.signature_picture)
        else:
            signature_picture_url = ''
        if user_obj.enclosure:
            enclosure_url = '/media/' + str(user_obj.enclosure)
        else:
            enclosure_url = ''

        user_data = {"real_name": user_obj.real_name, "username": user_obj.job_number, "department": user_obj.company.name, "gender": "男" if user_obj.gender == "male" else "女",
                     "marital_status": "单身" if user_obj.marital_status == "single" else "已婚", "education": user_obj.education, "political_outlook": user_obj.political_outlook,
                     "nation": user_obj.nation, "ID_number": user_obj.ID_number, "native_place": user_obj.native_place, "major": user_obj.major, "jon_degree": user_obj.first_degree,
                     "graduated_university": user_obj.graduated_university, "position": user_obj.position, "home_address": user_obj.home_address, "mobile": user_obj.mobile,
                     "mailbox": user_obj.mailbox, "remarks": user_obj.remarks, "signature_picture": signature_picture_url, "enclosure": enclosure_url}
        returnDict = {'code': 200, 'message': '获取成功！', "data": user_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UploadRoster(View):
    def post(self, request):
        RosterFile = request.FILES.get('files')
        # company_list = {"住院收费室": 23, "心功能室": 74, "支助中心": 15, "门诊产科": 69, "康复医学·中医科": 46, "神经外科·烧伤科·血管外科": 59, "骨外三科": 58, "骨外二科": 57, "院感办": 6, "门收门挂": 23,
        #                 "门诊妇科": 69, "门办": 25, "普外1科": 53, "外联部": 5, "招标办": 9, "工会": 7, "经管办": 10}
        workbook = xlrd.open_workbook(file_contents=RosterFile.read())
        worksheet = workbook.sheet_by_index(0)
        if worksheet.nrows > 2:
            for row_index in range(1, worksheet.nrows):
                row_data = worksheet.row_values(row_index)
                pwd = "pbkdf2_sha256$216000$pGoZOuJ5GMXw$xEtwcJyLJOB2Z44krkBKFQz8DTL5eWUaU3SqMtS7zWU="
                try:
                    company_obj = Company.objects.get(name=row_data[2].strip())
                except:
                    returnDict = {'code': 400, 'message': f'请检查 {row_data[0].strip()} 所在科室名称！', "data": []}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                User.objects.create(
                    password=pwd, is_superuser=0, username=str(int(row_data[1])), first_name="", last_name="",
                    email="", is_staff=0, job_number=str(int(row_data[1])),
                    personnel_code=str(int(row_data[1])), real_name=str(row_data[0]).strip(),
                    department=str(row_data[2]).strip(), department_code="", personnel_category="",
                    gender="male" if str(row_data[5]).strip() == "男" else "female",
                    birthday_date='', regular_time="", personnel_attributes="", jon_degree=str(row_data[6]).strip(),
                    admission_in_time=str(row_data[8]).strip(), mobile=str(row_data[3]).strip(), station="",
                    resignation_time="", rank="", employee_identity="", post='', position='',
                    positions_grade=str(row_data[6]).strip(), first_degree=str(row_data[6]).strip(),
                    autograph="", nation=str(row_data[4]).strip(), ID_number=str(row_data[9]).strip(), native_place='', major='',
                    graduated_university='', is_synchronize_personnel_file=0, political_outlook="群众", birthday=' ',
                    is_mobile_access=0, user_status="", schedule_type="", role=str(row_data[7]).strip(),
                    superior="", subordinate="", management_scope="", serial_number=0, region="", country="中国",
                    province="", city="", workplace="", job_category="", is_delete=0, education=str(row_data[6]).strip(),
                    age=0, mailbox="", QQ="", wechat_number="", office_telephone="", home_address="",
                    remarks="", level=6, company=company_obj, group_id=6
                )

        returnDict = {'code': 200, 'message': '更新成功！', "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class Authorizationverification(LoginRequiredMixin, View):
    def post(self, request):
        power_type = request.POST.get("power_type", 1)
        flag = 'false'
        if int(power_type) == 1:
            obj_count = request.user.evaluationopinion_set.filter(node='one').count()
            com_count = Company.objects.filter(head_people=request.user).count()
            if obj_count or com_count:
                flag = 'true'
        else:
            obj_count = Staffing.objects.filter(station='医德医风考核人', post_personnel=request.user).count()
            DZB_obj = Company.objects.get(id=3).head_people
            if obj_count or request.user == DZB_obj:
                flag = 'true'
        returnDict = {'code': 200, 'message': '查询成功！', 'flag': flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ScanQRCodeToSignIn(View):
    def get(self, request):
        uuids = uuid.uuid4()
        urls = f"https://oa.whmdtechnology.com/system-setup/GetScanQRCodeData?uuid={uuids}"
        img = qrcode.make(urls)
        img_path = os.getcwd() + f"/media/ScanQrImg/{uuids}.png"
        with open(img_path, 'wb') as f:
            img.save(f)
        return render(request, "system_setup/ScanQRCode.html", {"img_path": f"/media/ScanQrImg/{uuids}.png"})

class GetScanQRCodeData(View):
    def get(self, request):
        uuids = request.GET.get("uuid", "")
        return HttpResponse("签到成功！")

class topic_leave(View):
    def post(self, request):
        job_number = request.POST.get("job_number", '')
        reason = request.POST.get("reason", '')
        topic_type = request.POST.get("topic_type", '')
        topic_year = request.POST.get("topic_year", '')
        topic_num = request.POST.get("topic_num", '')


        sing_obj = topic_sing.objects.filter(leaders=User.objects.get(job_number=job_number), meet_number=topic_num, topic_type=topic_type, topic_year=topic_year, sing_type="2")
        if sing_obj.count():
            returnDict = {'code': 400, 'message': '已请过假，无需重复操作！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        topic_sing.objects.create(leaders=User.objects.get(job_number=job_number), sing_time=datetime.now().strftime("%Y-%m-%d %H:%M"), meet_number=topic_num, topic_type=topic_type,
                                  topic_year=topic_year, reason=reason, sing_type="2")
        returnDict = {'code': 200, 'message': '请假成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")